package edu.virginia.cs4501.team22.services;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.jws.WebService;

@WebService(targetNamespace = "http://services.team22.cs4501.virginia.edu/", endpointInterface = "edu.virginia.cs4501.team22.services.BuildingFinderEndpoint", portName = "BuildingFinderPort", serviceName = "BuildingFinderService")
public class BuildingFinder implements BuildingFinderEndpoint {
	
	private static final String USERNAME = "cs4501wgs4c";
	private static final String PASSWORD = "P3md4S!";
	private static final String URL = "jdbc:mysql://stardock.cs.virginia.edu/cs4501wgs4c";
	
	private Connection database;
	
	public float getCoordinate(String buildingName, int responsePart) {
		float ret = 0.0F;
		String sqlstring, coordinate;
		
		try {
			//Next two lines establish a connection to the database of building coordinates
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			database = DriverManager.getConnection(URL, USERNAME, PASSWORD);

			if (responsePart == 0)
				coordinate = "y_coordinate";
			else
				coordinate = "x_coordinate";
			
			sqlstring = "SELECT " + coordinate +
					" FROM `gps_data` " +
					"WHERE building_name = \"" + buildingName + "\"";
			
			PreparedStatement statement = database.prepareStatement(sqlstring);
			ResultSet rs = statement.executeQuery();
			int div = 0;
			while (rs.next()) {
				ret += Float.valueOf(rs.getString(coordinate));
				div++;
			}
			ret /= div;
		} catch (Exception e) {
			System.out.println(e);
			ret = -180.0F;
		} finally {
			try {
				if (!database.isClosed())
					database.close();
			} catch (SQLException e) {
			}
		}
		return ret;
	}
	
	public static void main(String args[]) {
		String arg = "Alderman Library";
		System.out.println(new BuildingFinder().getCoordinate(arg, 0));
		System.out.println(new BuildingFinder().getCoordinate(arg, 1));
	}
}